package cloud.shyidong.admin.commerce.service;

import cloud.shyidong.commerce.dao.CommerceCategoryDao;
import cloud.shyidong.commerce.dao.CommerceGoodsDao;
import cloud.shyidong.commerce.entity.CommerceCategoryEntity;
import cloud.shyidong.commerce.entity.CommerceGoodsEntity;
import cloud.shyidong.commerce.request.CommerceGoodsInsertRequest;
import cloud.shyidong.commerce.request.CommerceGoodsPageRequest;
import cloud.shyidong.commerce.request.CommerceGoodsUpdateRequest;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.request.LongIdRequest;
import cloud.shyidong.core.service.AbstractService;
import cloud.shyidong.core.util.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 电商商品业务处理
 * </p>
 *
 * @author syd
 * @since 2023-09-18 15:34:23
 */
@Service
public class CommerceGoodsService extends AbstractService<CommerceGoodsDao, CommerceGoodsEntity, LongIdRequest, CommerceGoodsInsertRequest, CommerceGoodsUpdateRequest, CommerceGoodsPageRequest> {
    
    private CommerceCategoryDao commerceCategoryDao;
    
    @Autowired
    public void setCommerceCategoryDao(CommerceCategoryDao commerceCategoryDao) {
        this.commerceCategoryDao = commerceCategoryDao;
    }
    
    @Override
    public void beforeUpdate(CommerceGoodsUpdateRequest updateRequest) {
        
        CommerceGoodsEntity commerceGoodsEntity = getDao().selectById(updateRequest.getId());
        if (ObjectUtils.isNull(commerceGoodsEntity)) {
            throw BusinessException.from("未查找到商品");
        }
        
        QueryWrapper<CommerceGoodsEntity> goodsGoodsEntityQueryWrapper = new QueryWrapper<>();
        goodsGoodsEntityQueryWrapper.eq("tenant_id", commerceGoodsEntity.getTenantId());
        goodsGoodsEntityQueryWrapper.and(queryWrapper -> queryWrapper.eq("name", updateRequest.getName()).or().eq("display_name", updateRequest.getDisplayName()));
        goodsGoodsEntityQueryWrapper.ne("id", updateRequest.getId());
        if (getDao().selectCount(goodsGoodsEntityQueryWrapper) > 0) {
            throw BusinessException.from("商品名称或商品显示名称已经重复");
        }
        
    }
    
    @Override
    public Map<String, Object> view(LongIdRequest idRequest) {
        Map<String, Object> result = super.view(idRequest);
        Long categoryId = (Long) result.get("categoryId");
        CommerceCategoryEntity commerceCategoryEntity = commerceCategoryDao.selectById(categoryId);
        result.put("categoryName", commerceCategoryEntity.getName());
        return result;
    }
    
}
